package com.itshen.jmh;

import org.openjdk.jmh.annotations.*;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

@BenchmarkMode({Mode.Throughput, Mode.AverageTime}) // 测试方法平均执行时间
@OutputTimeUnit(TimeUnit.SECONDS) // 输出结果的时间粒度为微秒
@State(Scope.Benchmark) // 每个测试线程一个实例
public class JMHQueueTest {

    static CopyOnWriteArrayList smallCopyOnWriteList = new CopyOnWriteArrayList();
    static ConcurrentLinkedQueue smallConcurrentList = new ConcurrentLinkedQueue();
    static CopyOnWriteArrayList bigCopyOnWriteList = new CopyOnWriteArrayList();
    static ConcurrentLinkedQueue bigConcurrentList = new ConcurrentLinkedQueue();


    @Setup
    public void setup() {
        for (int i = 0; i < 10; i++) {
            smallCopyOnWriteList.add(new Object());
            smallConcurrentList.add(new Object());
        }

        for (int i = 0; i < 1000; i++) {
            bigCopyOnWriteList.add(new Object());
            bigConcurrentList.add(new Object());
        }
    }

    @Benchmark
    public void copyOnWriteGet() {
        smallCopyOnWriteList.get(0);
    }

    @Benchmark
    public void copyOnWriteSize() {
        smallCopyOnWriteList.size();
    }

    @Benchmark
    public void concurrentGet() {
        smallConcurrentList.peek();
    }

    @Benchmark
    public void concurrentSize() {
        smallConcurrentList.size();
    }

    @Benchmark
    public void smallCopyOnWriteWrite() {
        smallCopyOnWriteList.add(new Object());
        smallCopyOnWriteList.remove(0);
    }

    @Benchmark
    public void smallConcurrentWrite() {
        smallConcurrentList.add(new Object());
        smallConcurrentList.remove(0);
    }

    @Benchmark
    public void bigCopyOnWriteWrite() {
        bigCopyOnWriteList.add(new Object());
        bigCopyOnWriteList.remove(0);
    }

    @Benchmark
    public void bigConcurrentWrite() {
        bigConcurrentList.offer(new Object());
        bigConcurrentList.remove(0);
    }
}
